package com.mall.order.services;

import com.mall.order.CancelOrderService;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.OrderMapper;
import com.mall.order.dal.persistence.StockMapper;
import com.mall.order.dto.CancelOrderRequest;
import com.mall.order.dto.CancelOrderResponse;
import com.mall.order.utils.ExceptionProcessorUtils;
import com.mall.user.constants.SysRetCodeConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * create by heyyon 2020-12-22 10:40
 */
@Service
@Slf4j
@Component
public class CancelOrderServiceImpl implements CancelOrderService {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderItemMapper orderItemMapper;
    @Autowired
    StockMapper stockMapper;
    @Override
    public CancelOrderResponse cancelOrderById(CancelOrderRequest cancelOrderRequest) {
        CancelOrderResponse cancelOrderResponse = new CancelOrderResponse();
        try {
            String id=cancelOrderRequest.getOrderId();
            Integer updateOrderRow=orderMapper.updateStatusById(id);
            if (updateOrderRow == 0) {
                cancelOrderResponse.setCode(SysRetCodeConstants.SYSTEM_ERROR.getCode());
                cancelOrderResponse.setMsg("订单不存在");
                return cancelOrderResponse;
            }
            Integer updateOrderItemRows = orderItemMapper.updateStatusByOrderId(cancelOrderRequest.getOrderId());
            List<Long> goodIds = orderItemMapper.selectGoodIds(cancelOrderRequest.getOrderId());
            for (Long goodId : goodIds) {
                Integer num = orderItemMapper.selectNumByOrderIdAndGoodId(cancelOrderRequest.getOrderId(), goodId);
                stockMapper.updateGoodsStockById(goodId,num);
            }
            cancelOrderResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
            cancelOrderResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        } catch (Exception e) {
            log.error("CancelOrderServiceImpl.cancelOrderById Occur Exception:"+e);
            ExceptionProcessorUtils.wrapperHandlerException(cancelOrderResponse,e);
        }
        return cancelOrderResponse;
    }
}
